package com.github.phoenics.teacher.itheima.netty.jdkSerializable;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;

/**
 * @author Phoenics Chow
 * on 2020年04月18日
 */
public class JsonSerializationUtil {
    public static   String serialize(Object t) {
        // JSON对象序列化
        String employeeJson = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            StringWriter stringWriter = new StringWriter();
            JsonGenerator jsonGenerator = new JsonFactory().createJsonGenerator(stringWriter);
            objectMapper.writeValue(jsonGenerator, t);
            jsonGenerator.close();
            employeeJson = stringWriter.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return employeeJson;
    }

    public static <T> T deserialize(String json,Class<T> tclass) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(json, tclass);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
